package cn.com.czpb.client.module.news.activity;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.config.CODE;
import cn.com.czpb.client.model.news.IsCollectionEntity;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.SubJectTypeBean;
import cn.com.czpb.client.model.usercenter.LevelEntity;
import cn.com.czpb.client.module.dialog.ShareDialog;
import cn.com.czpb.client.module.personal.WodeFragment;
import cn.com.czpb.client.module.personal.acticity.LoginActivity;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * Created by 猪猪侠 on 2017/8/25.
 */
public class ZhuantiActivityNew extends MToolBarActivity{
    @BindView(R.id.zhuanti_name)
    TextView zhuantiname;
    @BindView(R.id.myztwebview)
    WebView mWebView;
    @BindView(R.id.img_share)
    ImageView img_share;
    @BindView(R.id.img_collection)
    ImageView img_collect;
    @BindView(R.id.ll_back_1)
    LinearLayout backll;
    private NewsBean newsBean;
    private int textsize;
    @Override
    protected int setLayoutId() {
        return R.layout.activity_zhuanti_new;
    }
    @Override
    public void initView() {
        textsize = spu.getTextSize();
        WebSettings webSettings = mWebView .getSettings();
        webSettings.setJavaScriptEnabled(true); //支持js
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setSupportZoom(false);//不能缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8"); //设置编码格式
        webSettings.setPluginState(WebSettings.PluginState.OFF); //设置是否支持flash插件
        webSettings.setDefaultFontSize(20); //设置默认字体大小
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                view.loadUrl(url);
                return false;

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                addImageClickListner();
            }
        });
        setWebViewTextSize(textsize);
//        mWebView.addJavascriptInterface(this,"imagelistner");
    }
    @OnClick(R.id.ll_back_1)
    public void doclick(){
        if(mWebView.canGoBack()){
            mWebView.goBack();
        }else{
            finish();
        }
    }
    private void setWebViewTextSize(int textSize) {
        LogUtils.e("setWebViewTextSize 字体-->2" + textSize);
        WebSettings settings = mWebView.getSettings();
        WebSettings.TextSize t = null;
        switch (textSize) {
            case CODE.textSize_big:
                settings.setTextZoom(115);
                break;
            case CODE.textSize_normal:
                settings.setTextZoom(100);
                break;
            case CODE.textSize_small:
                settings.setTextZoom(80);
                break;
            default:
                settings.setTextZoom(100);
                break;
        }
//        mWebView.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
    }
    @android.webkit.JavascriptInterface
    public void openImage(String img) {
        Intent intent = new Intent();
        intent.putExtra("imgurl",img);
        intent.setClass(activity,ImgActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }
    // 注入js函数监听
    private void addImageClickListner() {
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，
        //函数的功能是在图片点击的时候调用本地java接口并传递url过去
        mWebView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistner.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");
    }
    @Override
    public void initData() {
        Intent intent = getIntent();
        newsBean = (NewsBean) intent.getSerializableExtra("newbean");
        mWebView.loadUrl(newsBean.getNewsurl());
        if(spu.getUser()!=null) {
            isCollection();
        }
    }
    //是否收藏
    private void isCollection() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() == null) {
            return;
        }
        map.put("typeid", newsBean.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "1");
        Factory.provideHttpService()
                .newsIsCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200收藏-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)) {
                            if ("1".equals(entity.data.getStatus())) {
                                img_collect.setImageResource(R.drawable.tabbar_collect_light);
                            }
                        } else {
                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }
    @OnClick({R.id.img_share,R.id.img_collection})
    public void shareorcollect(View view){
        switch (view.getId()){
            case R.id.img_share:
                if(spu.getUser() != null) {
                    String imgurl = null;
                    if (null != newsBean.getImgs() && newsBean.getImgs().size() > 0) {
                        imgurl = newsBean.getImgs().get(0);
                    }
                    String sharelink = mWebView.getUrl();
                    ShareDialog dialog = new ShareDialog(activity, R.style.Sharedialog, newsBean.getTitle(), sharelink, imgurl, 1);
                    dialog.show();
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.img_collection:
                if (spu.getUser() != null) {
                    addCollection();
                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    activity.startActivityForResult(intent,112);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 112){
            isCollection();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if(mWebView.canGoBack()){
                mWebView.goBack();
            }else{
                finish();
            }
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
    // 添加收藏
    private void addCollection() {
        Map<String, String> map = new HashMap<>();
        map.put("typeid", newsBean.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "1");
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsAddCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)) {
                            if ("1".equals(entity.data.getStatus())) {
                                TUtils.toast("收藏成功");
                                initlevel();
                                img_collect.setImageResource(R.drawable.tabbar_collect_light);
                            } else {
                                img_collect.setImageResource(R.drawable.tabbar_collect);
                                TUtils.toast("收藏取消");
                            }
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }

    private void initlevel() {
        String uid = spu.getUser().getUid();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        Factory.provideHttpService().MyLevel(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LevelEntity, Boolean>() {
                    @Override
                    public Boolean call(LevelEntity levelEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LevelEntity>() {
                    @Override
                    public void call(LevelEntity levelEntity) {
                        LogUtils.e("code--" + levelEntity.code);
                        if ("200".equals(levelEntity.code)) {
                            spu.getUser().setUlevel("Lv" + levelEntity.data.getUserinfo().getLevel());
                            Intent intent = new Intent();
                            intent.setAction(WodeFragment.ACTION_USER);
                            activity.sendBroadcast(intent);

                        } else {
                            TUtils.toast(levelEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }
    private void getServerList(final SubJectTypeBean data) {

    }


    public void setListData(List<NewsBean> list) {

    }
}
